package cn.com.chengmandian.rabbitmq.event;

import cn.com.chengmandian.rabbitmq.constants.RabbitMqConstants;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class EventService {

  @Autowired
  private RabbitTemplate rabbitTemplate;

  /**
   * 发送事件
   */
  public void sendEvent(String code, JSONObject data, String source) {
    this.sendEvent(code, data, source, false);
  }

  /**
   * 发送事件
   */
  public void sendEvent(String code, JSONObject data, String source, boolean isLog) {
    EventInfo eventInfo = new EventInfo()
        .setCode(code)
        .setData(data)
        .setSource(source)
        .setLog(isLog)
        .setCreateTime(new Date());
    this.sendEvent(eventInfo);
  }

  /**
   * 发送事件
   */
  public void sendEvent(EventInfo eventInfo) {
    try {
      if (eventInfo.isLog()) {
        log.error("收到事件消息：{}", JSONObject.toJSONString(eventInfo));
      }
      rabbitTemplate.convertAndSend(RabbitMqConstants.EVENT_EXCHANGE, eventInfo.getCode(), eventInfo);
    } catch (Exception e) {
      log.error("发送事件失败", e);
    }
  }
}
